//
//  Utils.swift
//  Solenoid
//
//  Created by Rail on 2/16/16.
//  Copyright © 2016 Rail. All rights reserved.
//

import UIKit
import AudioToolbox


@objc(Utils)

class Utils: NSObject {
    // MARK: - LoadingIndicator
    
    static let loadingIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
    
    class func showLoading() {
        let keyWindow = UIApplication.shared.keyWindow?.rootViewController?.view
        if loadingIndicator.superview == keyWindow {return }
        keyWindow?.isUserInteractionEnabled = false
        loadingIndicator.color = UIColor.gray
        keyWindow?.addSubview(loadingIndicator)
        loadingIndicator.center = (keyWindow?.center)!
       
        loadingIndicator.startAnimating()
    }
    
    class func hideLoading() {
        let keyWindow = UIApplication.shared.keyWindow?.rootViewController?.view
        keyWindow?.isUserInteractionEnabled = true
        loadingIndicator.stopAnimating()
        loadingIndicator.removeFromSuperview()
    }

    // MARK: - LoadingView
    
    struct LoadingView {
        var view:UIView = UIView()
        var indicator:UIActivityIndicatorView = UIActivityIndicatorView()
        var messageLabel:UILabel = UILabel()
        
        init() {
//            view.frame = CGRectMake(0, 0, 120, 80)
            view.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: 120, height: 80))

            view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
            view.layer.cornerRadius = 5
            view.addSubview(indicator)
            view.addSubview(messageLabel)
//            indicator.frame = CGRectMake(50, 10, 20, 20)
            indicator.frame = CGRect.init(origin: CGPoint.init(x: 50, y: 10), size: CGSize.init(width: 20, height: 20))
            indicator.startAnimating()
//            messageLabel.frame = CGRectMake(10, 40, 100, 40)
            messageLabel.frame = CGRect.init(origin: CGPoint.init(x: 10, y: 40), size: CGSize.init(width: 100, height: 40))
            messageLabel.textColor = UIColor.white
//            messageLabel.font = UIFont.systemFontOfSize(20)
            messageLabel.font = UIFont.systemFont(ofSize: 20)
            messageLabel.textAlignment = NSTextAlignment.center
            
        }
    }
    
    static let loadingView:LoadingView = LoadingView()
    
    class func showLoadingView(message:String) {
        let keyWindow = UIApplication.shared.keyWindow?.rootViewController?.view
        keyWindow?.isUserInteractionEnabled = false
        loadingView.messageLabel.text = message
        showView(view: loadingView.view)
    }
    
    class func palySoundWheel() {
        var soundIDWheel:SystemSoundID = 1
        let pathWheel = Bundle.main.path(forResource: "wheel_01", ofType: "mp3")!
        AudioServicesCreateSystemSoundID(NSURL(fileURLWithPath: pathWheel), &soundIDWheel)
        AudioServicesPlaySystemSound(soundIDWheel)
//        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
    }
    
    
    //隐藏载入Loading
    class func hideLoadingView() {
        UIApplication.shared.keyWindow?.rootViewController?.view.isUserInteractionEnabled = true
        hideView(view: loadingView.view)
    }
    
    // MARK: - TipMessageView
    
    struct TipMessage {
        var view:UIView = UIView()
        var messageLabel:UILabel = UILabel()
        
        init(message:String) {
            let msg = NSString(string: message)
            let size = msg.size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20)])
//            let frame = CGRectMake(0, 0, size.width, 40)
            let frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: CGSize.init(width: size.width, height: 40))
            view.frame = frame
            view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7)
            view.layer.cornerRadius = 5
            view.addSubview(messageLabel)
            messageLabel.frame = frame
            messageLabel.textColor = UIColor.white;
            messageLabel.font = UIFont.systemFont(ofSize: 14)
            messageLabel.textAlignment = NSTextAlignment.center
            messageLabel.text = message
        }
    }
    
    //提示框
    class func showTipMessage(tipMessage:String)  {
        let tipMessageView = TipMessage(message: tipMessage)
        
        showView(view: tipMessageView.view)
        
//        Timer.scheduledTimerWithTimeInterval(1.5, target: self, selector:#selector(Utils.hideTipMessage(_:)), userInfo: tipMessageView.view, repeats: false)
        Timer.scheduledTimer(timeInterval: 1.5, target: self, selector:#selector(Utils.hideTipMessage(timer:)), userInfo: tipMessageView.view, repeats: false)
        
    }
    
    class func playBtnSound(){
        AudioServicesPlaySystemSound(1057)
    
    }
    
    @objc class private func hideTipMessage(timer:Timer) {
        hideView(view: timer.userInfo as! UIView)
    }
    
    // MARK: - Private Methods
    
    class private func showView(view:UIView) {
        let keyWindow = UIApplication.shared.keyWindow?.rootViewController?.view
       
        keyWindow?.addSubview(view)
        let center = (keyWindow?.center)!
        view.center = CGPoint(x: center.x, y: center.y - 50)
        view.isHidden = false
        view.alpha = 0
        UIView.animate(withDuration: 0.3) { () -> Void in
            view.alpha = 1
        }
    }
    
    class private func hideView(view:UIView) {
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            view.alpha = 0
            }) { (finished:Bool) -> Void in
                if finished {
                    view.removeFromSuperview()
                }
        }
    }
    
    // MARK: - UIAlertView
    
    class func showAlertMessage(errorMessage:String) {
        let alertView = UIAlertView(title: "错误", message: errorMessage, delegate: nil, cancelButtonTitle: "OK")
        alertView.show()
    }
    
}


extension Utils {
    //MARK: - timer 
    
    class func getTimerResultForIndex(timerStr:String, index:Int) -> String? {
        let reg = try? NSRegularExpression(pattern: "^P\\[(0x\\d*\\w*)\\]T\\[(\\d+)\\]A\\[(\\d+)\\]$", options: .caseInsensitive)
        return reg?.stringByReplacingMatches(in: timerStr, options: .reportCompletion, range: NSRange(location: 0, length: timerStr.characters.count), withTemplate:"$\(index)")
        
    }
    
    
    class func getStringFromPattern(str:String, pattern:String) -> String? {
        let reg = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        if let result = reg?.firstMatch(in: str, options: .reportCompletion, range: NSRange(location: 0, length: str.characters.count)) {
            let resultString = (str as NSString).substring(with: result.range)
            
            return reg?.stringByReplacingMatches(in: resultString, options: .reportCompletion, range: NSRange(location: 0, length: resultString.characters.count), withTemplate:"$1")
        }else {
            return ""
        }
    }
}


extension Utils {
    //MARK:- notification
    
    class func showNotification(message:String) {
        let width = UIScreen.main.bounds.width
        let messageView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: 44))
        messageView.backgroundColor = UIColor.black
        
        let messageLabel = UILabel(frame: CGRect(x: 0, y: 11, width: width, height: 22))
        messageLabel.text = message
        messageLabel.textAlignment = .center
        messageLabel.textColor = UIColor.white
        messageLabel.font = UIFont.systemFont(ofSize: 16)
        messageView.addSubview(messageLabel)
        
        let navigationController = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController
        navigationController?.navigationBar.addSubview(messageView)
        showNotificationView(view: messageView)
        
    }
    
    private class func showNotificationView(view:UIView) {
        let frame = view.frame
        view.frame = CGRect(x: 0, y: -64, width: frame.width, height: frame.height)
        
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            view.frame = frame
            }) { (finished) -> Void in
                if finished {
                    Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(Utils.hideNotificationView(timer:)), userInfo: view, repeats: false)
                }
        }
        
        
    }
    
    @objc private class func hideNotificationView(timer:Timer) {
        let view = timer.userInfo as! UIView
        let frame = view.frame
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            view.frame = CGRect(x: 0, y: -64, width: frame.width, height: frame.height)
            }) { (finished) -> Void in
                if finished {
                    view.removeFromSuperview()
                }
        }
    }
}


